package com.ledim.share;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.ledim.app.LeDimApplication;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimBaseUtils;
import com.ledim.utils.LedimBitmapUtils;
import com.ledim.utils.ToastUtil;
import com.letv.android.young.client.R;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.net.AsyncWeiboRunner;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.net.WeiboParameters;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 分享工具类
 *
 * @author ccx
 */
public class LedimShareUtil {

    /**
     * 分享文本到微信
     *
     * @param text
     *         文本内容
     * @param isCircle
     *         是否分享到朋友圈
     */
    public static void shareTextToWechat(String text, boolean isCircle) {
        if (LedimBaseUtils.isEmpty(text)) {
            return;
        }

        // 初始化一个WXTextObject对象
        WXTextObject textObj = new WXTextObject();
        textObj.text = text;

        // 用WXTextObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        // 发送文本类型的消息时，title字段不起作用
        // msg.title = "Will be ignored";
        msg.description = text;
        shareToWechat("text", msg, isCircle);
    }

    /**
     * 分享图片到微信
     *
     * @param source
     *         图片资源
     * @param isCircle
     *         是否分享到朋友圈
     */
    public static void shareImgToWechat(Bitmap source, boolean isCircle) {
        if (source == null) {
            return;
        }

        WXImageObject imgObj = new WXImageObject(source);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        msg.thumbData = LedimBitmapUtils.revitionImageSize(source, 150, 20 * 1024);
        if (source != null) {
            source.recycle();
        }

        shareToWechat("img", msg, isCircle);
    }

    /**
     * 分享图片到微信
     *
     * @param filePath
     *         图片文件地址
     * @param isCircle
     *         是否分享到朋友圈
     */
    public static void shareLocalImgToWechat(String filePath, boolean isCircle) {
        if (filePath == null) {
            return;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }

        WXImageObject imgObj = new WXImageObject();
        imgObj.setImagePath(filePath);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap thumb = LedimBitmapUtils.getBitmap(filePath, 150, true);
        if (thumb != null) {
            msg.thumbData = LedimBitmapUtils.revitionImageSize(thumb, 150, 20 * 1024);
            if (thumb != null) {
                thumb.recycle();
            }
        }

        shareToWechat("img", msg, isCircle);
    }

    /**
     * 分享图片到微信
     *
     * @param thumbUrl
     *         图片url
     * @param isCircle
     *         是否是朋友圈
     */
    public static void shareImgToWechat(String thumbUrl, final boolean isCircle) {
        if (!LedimBaseUtils.isEmpty(thumbUrl)) {
            ImageRequest request =
                    ImageRequestBuilder.newBuilderWithSource(Uri.parse(thumbUrl)).build();
            DataSource<CloseableReference<CloseableImage>> dataSource = Fresco.getImagePipeline()
                                                                              .fetchDecodedImage(request, LeDimApplication
                                                                                      .getInstance()
                                                                                      .getApplicationContext());
            dataSource.subscribe(new BaseBitmapDataSubscriber() {
                @Override
                public void onNewResultImpl(@Nullable Bitmap bitmap) {
                    // You can use the bitmap here, but in limited ways.
                    // No need to do any cleanup.
                    shareImgToWechat(bitmap, isCircle);
                }

                @Override
                public void onFailureImpl(DataSource dataSource) {
                    // No cleanup required here.
                }
            }, CallerThreadExecutor.getInstance());

        }
    }

    /**
     * 分享网页到微信
     *
     * @param url
     *         网页地址
     * @param title
     *         网页标题
     * @param description
     *         网页描述
     * @param thumbSource
     *         网页缩略图资源
     * @param isCircle
     *         是否分享到朋友圈
     */
    public static void shareWebpageToWechat(String url, String title, String description,
                                            Bitmap thumbSource, boolean isCircle) {
        if (LedimBaseUtils.isEmpty(url)) {
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;

        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = LedimBaseUtils.trim(title);
        msg.description = LedimBaseUtils.trim(description);
        if (thumbSource != null) {
            msg.thumbData = LedimBitmapUtils.revitionImageSize(thumbSource, 150, 20 * 1024);
            // if (thumbSource != null)
            // {
            // thumbSource.recycle();
            // }
        }

        shareToWechat("webpage", msg, isCircle);
    }

    /**
     * 分享网页到微信
     *
     * @param url
     *         网页地址
     * @param title
     *         网页标题
     * @param description
     *         网页描述
     * @param thumbPath
     *         网页缩略图地址
     * @param isCircle
     *         是否分享到朋友圈
     */
    public static void shareWebpageToWechat(String url, String title, String description,
                                            String thumbPath, boolean isCircle) {
        if (LedimBaseUtils.isEmpty(url)) {
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;

        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = LedimBaseUtils.trim(title);
        msg.description = LedimBaseUtils.trim(description);
        if (thumbPath != null) {
            File file = new File(thumbPath);
            if (file.exists()) {
                Bitmap thumb = LedimBitmapUtils.getBitmap(thumbPath, 150, true);
                if (thumb != null) {
                    if (TextUtils.isEmpty(msg.title) && TextUtils.isEmpty(msg.description)) {
                        msg.mediaObject =
                                new WXImageObject(LedimBitmapUtils.revitionImageSize(thumb, 150,
                                        20 * 1024));
                    } else {
                        msg.thumbData = LedimBitmapUtils.revitionImageSize(thumb, 150, 20 * 1024);
                    }
                    if (thumb != null) {
                        thumb.recycle();
                    }
                }
            }

        }

        shareToWechat("webpage", msg, isCircle);
    }

    /**
     * 分享网页到微信
     *
     * @param url
     *         网页地址
     * @param title
     *         网页标题
     * @param description
     *         网页描述
     * @param thumbUrl
     *         网页缩略图地址
     * @param isCircle
     *         是否分享到朋友圈
     * @param parentView
     *         点击的view
     */
    public static void shareWebpageToWechat(final String url, final String title,
                                            final String description, final String thumbUrl,
                                            final boolean isCircle, final View parentView) {
        if (LedimBaseUtils.isEmpty(thumbUrl)) {
            shareWebpageToWechat(url, title, description, "", isCircle);
        } else {
            FrescoUtil.getBitmap(thumbUrl, LeDimApplication.getInstance()
                                                           .getApplicationContext(), 0, 0, new FrescoUtil.BitmapListener() {
                @Override
                public void onSuccess(Bitmap bitmap, InputStream inputStream) {
                    shareWebpageToWechat(url, title, description, bitmap, isCircle);
                }

                @Override
                public void onFail() {
                    shareWebpageToWechat(url, title, description, "", isCircle);
                }
            });
        }
    }

    /**
     * 分享到微信
     *
     * @param type
     *         分享类型
     * @param msg
     *         分享内容
     * @param isCircle
     *         是否分享到朋友圈
     */
    private static void shareToWechat(String type, WXMediaMessage msg, boolean isCircle) {
        IWXAPI api =
                WXAPIFactory.createWXAPI(LeDimApplication.getInstance(), ConstantUtil.ShareConstant.WEIXIN_APP_ID, true);
        if (api.isWXAppInstalled()) {
            api.registerApp(ConstantUtil.ShareConstant.WEIXIN_APP_ID);
            // 构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction =
                    buildTransaction(LedimBaseUtils.trim(type)); // transaction字段用于唯一标识一个请求
            req.message = msg;
            req.scene = isCircle ? SendMessageToWX.Req.WXSceneTimeline
                                 : SendMessageToWX.Req.WXSceneSession;
            // 调用api接口发送数据到微信
            api.sendReq(req);
        } else {
            ToastUtil.toast(R.string.uninstall_wechat);
        }

    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                              : type + System.currentTimeMillis();
    }

    /**
     * 分享到QQ控件
     *
     * @param args
     *         默认第一个参数 SHARE_TO_QQ_TITLE
     *         参数二 SHARE_TO_QQ_SUMMARY
     *         参数三 SHARE_TO_QQ_TARGET_URL
     *         参数四 SHARE_TO_QQ_IMAGE_URL
     */
    public static void sharToQZONE(Activity activity, String... args) {
        Tencent mTencent =
                Tencent.createInstance(ConstantUtil.ShareConstant.QQZone_API_ID, LeDimApplication.getInstance());

        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        for (int i = 0; i < args.length; i++) {
            switch (i) {
                case 0:
                    params.putString(QzoneShare.SHARE_TO_QQ_TITLE, args[0]);
                    break;
                case 1:
                    params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, args[1]);
                    break;
                case 2:
                    params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, args[2]);
                    break;
                case 3:
                    params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL, args[3]);
                    break;
                default:
                    break;
            }
        }
        mTencent.shareToQQ(activity, params, new IUiListener() {
            @Override
            public void onCancel() {
                ToastUtil.toast("取消分享");
            }

            @Override
            public void onError(UiError e) {
                ToastUtil.toast("请重试");
            }

            @Override
            public void onComplete(Object response) {
                ToastUtil.toast("分享成功");
            }
        });
    }

    /**
     * @param activity
     * @param text
     * @param shareImageUrl
     *         sina微博分享
     */
    public static void shareToWeiBo(final Activity activity, final String text,
                                    String shareImageUrl) {
        final IWeiboShareAPI mWeiboShareAPI =
                WeiboShareSDK.createWeiboAPI(LeDimApplication.getInstance(), ConstantUtil.ShareConstant.SINA_APP_KEY);
        if (mWeiboShareAPI.isWeiboAppInstalled()) {
            mWeiboShareAPI.registerApp();
            if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
                if (supportApi >= 10351 /* ApiUtils.BUILD_INT_VER_2_2 */) {
                    if (!TextUtils.isEmpty(shareImageUrl)) {
                        File shareFile = new File(shareImageUrl);
                        if (shareFile.isFile() && shareFile.exists()) {
                            mWeiboShareAPI.sendRequest(activity, getWeiboMultiMessageReq(text, getLoacalBitmap(shareImageUrl)));
                        } else {
                            FrescoUtil.getBitmap(shareImageUrl, LeDimApplication.getInstance()
                                                                                .getApplicationContext(), 0, 0, new FrescoUtil.BitmapListener() {
                                @Override
                                public void onSuccess(Bitmap bitmap, InputStream inputStream) {
                                    mWeiboShareAPI.sendRequest(activity, getWeiboMultiMessageReq(text, bitmap));
                                }

                                @Override
                                public void onFail() {
                                    mWeiboShareAPI.sendRequest(activity, getWeiboMultiMessageReq(text, null));
                                    ToastUtil.toast("系统错误，请稍后重试");
                                }
                            });
                        }
                    }

                } else {
                    mWeiboShareAPI.sendRequest(activity, getWeiboSingleMessageReq(text));
                }

            } else {
                ToastUtil.toast(R.string.not_install_weiboclient);
            }

        }
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。 当{@link IWeiboShareAPI#getWeiboAppSupportAPI()}
     * < 10351 时，只支持分享单条消息，即 文本、图片、网页、音乐、视频中的一种，不支持Voice消息。
     */
    private static SendMessageToWeiboRequest getWeiboSingleMessageReq(String text) {
        // 1. 初始化微博的分享消息
        // 用户可以分享文本、图片、网页、音乐、视频中的一种
        WeiboMessage weiboMessage = new WeiboMessage();
        TextObject textObject = new TextObject();
        textObject.text = text;
        weiboMessage.mediaObject = textObject;

        // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        return request;
    }

    private static SendMultiMessageToWeiboRequest getWeiboMultiMessageReq(String text,
                                                                          Bitmap image) {
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        // 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
        TextObject textObject = new TextObject();
        textObject.text = text;
        weiboMessage.mediaObject = textObject;
        ImageObject imageObject = new ImageObject();

        if (image != null) {
            imageObject.setImageObject(image);
        } else {
            imageObject.setImageObject(BitmapFactory.decodeResource(LeDimApplication.getInstance()
                                                                                    .getResources(), R.drawable.login_icon));
        }
        weiboMessage.imageObject = imageObject;
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        // 3. 发送请求消息到微博，唤起微博分享界面
        return request;
    }

    /**
     * sina 分享 执行请求
     *
     * @param url
     * @param params
     * @param httpMethod
     * @param listener
     */
    private static void request(final String url, final WeiboParameters params,
                                final String httpMethod, RequestListener listener) {
        new AsyncWeiboRunner(LeDimApplication.getInstance()).requestAsync(url, params, httpMethod, listener);
    }

    /**
     * 发布一条新微博(连续两次发布的微博不可以重复)
     *
     * @param content
     *         要发布的微博文本内容，内容不超过140个汉字。
     * @param lat
     *         纬度，有效范围：-90.0到+90.0，+表示北纬，默认为0.0。
     * @param lon
     *         经度，有效范围：-180.0到+180.0，+表示东经，默认为0.0。
     * @param listener
     */
    public static void update(String content, String lat, String lon, String file, String token,
                              RequestListener listener) {
        WeiboParameters params = new WeiboParameters(ConstantUtil.ShareConstant.SINA_APP_KEY);
        params.put("access_token", token);
        params.put("source", ConstantUtil.ShareConstant.SINA_APP_KEY);
        params.put("status", content);
        if (!TextUtils.isEmpty(lon)) {
            params.put("lon", lon);
        }
        if (!TextUtils.isEmpty(lat)) {
            params.put("lat", lat);
        }
        if (!TextUtils.isEmpty(file)) {
            params.put("pic", file);
        }
        request(ConstantUtil.ShareConstant.SINA_SERVER +
                "statuses/update.json", params, "POST", listener);
    }

    //分享一张带网络图片的微博
    public static void updateImgWithURL(String content, String url, RequestListener listener) {
        WeiboParameters params = new WeiboParameters(ConstantUtil.ShareConstant.SINA_APP_KEY);
        params.put("status", content);
        params.put("url", url);
        request(ConstantUtil.ShareConstant.SINA_SERVER +
                "statuses/update.json", params, "POST", listener);
    }
    //
    ///**
    // * 退出登录
    // *
    // * @param listener
    // */
    //public static void endSession(RequestListener listener) {
    //    WeiboParameters params = new WeiboParameters();
    //    request(URL_ACCOUNT + / end_session.json, params, HTTPMETHOD_POST, listener);
    //}

    public static Bitmap getLoacalBitmap(String path) {
        try {
            FileInputStream fis = new FileInputStream(path);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
